package com.cxs.canvas2pixelmaptest.slice;

import com.cxs.canvas2pixelmaptest.ResourceTable;
import com.cxs.canvas2pixelmaptest.util.ImageUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.app.Environment;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice {
    Image image;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        image = (Image) findComponentById(ResourceTable.Id_image);
        // 把Canvas绘制的图形存储到PixelMap中
        PixelMap pixelMap = canvas2PixelMap();

        image.setPixelMap(pixelMap);
        // 编码
        try {
            encodingImage(pixelMap);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /*
        把Canvas绘制的图形存储到PixelMap中
     */
    private PixelMap canvas2PixelMap() {
        // 创建PixelMap图像
        PixelMap pixelMap = ImageUtils.createPixelMap(1000, 1800);
        // 创建Texture对象，用来存储绘图结果
        Texture texture = new Texture(pixelMap);
        // 创建画布，绘制的图形存储在texture中
        Canvas canvas = new Canvas(texture);
        // 创建画笔
        Paint paint = new Paint();
        paint.setTextSize(100);

        canvas.drawRect(0, 0, 1000, 1800, paint, Color.WHITE);

        paint.setColor(Color.BLACK);
        canvas.drawText(paint, "hello", 0, 200);
        canvas.drawCircle(400, 400, 200, paint);
        canvas.drawCircle(400, 400, 180, paint, Color.WHITE);
        // 返回绘制后的PixelMap
        return pixelMap;
    }

    /*
        把PixelMap图像编码后存储到手机中
     */
    private long encodingImage(PixelMap pixelMap) throws IOException {
        // 1.创建图像编码ImagePacker对象
        ImagePacker imagePacker = ImagePacker.create();
        // 2.编码输出流
        File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "new.jpeg");
        FileOutputStream fos = new FileOutputStream(file);
        // 3.编码参数
        ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
        packingOptions.format = "image/jpeg";
        packingOptions.quality = 100;
        // 4.设置输出流和编码参数
        boolean initialize = imagePacker.initializePacking(fos, packingOptions);
        // 5.添加要处理的PixelMap图像
        imagePacker.addImage(pixelMap);
        // 完成图像编码
        long dataSize = imagePacker.finalizePacking();

        fos.close();
        imagePacker.release();
        return dataSize;
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
